package com.project.harmonyledger.service.impl.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.project.harmonyledger.service.oss.FileService;
import com.project.harmonyledger.utils.oss.OSSConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传业务类
 *
 * @author lixiang
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

  @Autowired
  private OSSConfig ossConfig;

  /**
   * 阿里云OSS文件上传
   *
   * @param file
   */
  @Override
  public String upload(MultipartFile file) {
    // 创建OSSClient实例
    OSS ossClient = new OSSClientBuilder().build(
        ossConfig.getEndPoint(),
        ossConfig.getAccessKeyId(),
        ossConfig.getAccessKeySecret());

    try {
      // 生成文件路径
      String fileName = generateFileName(file.getOriginalFilename());

      // 上传文件
      ossClient.putObject(ossConfig.getBucketName(), fileName, file.getInputStream());

      // 生成访问URL
      return String.format("https://%s.%s/%s",
          ossConfig.getBucketName(),
          ossConfig.getEndPoint(),
          fileName);

    } catch (Exception e) {
      log.error("文件上传失败: {}", e.getMessage());
      throw new RuntimeException("文件上传失败: " + e.getMessage());
    } finally {
      ossClient.shutdown();
    }
  }

  /**
   * 生成文件名
   * 格式：user/年/月/日/随机UUID.扩展名
   */
  private String generateFileName(String originalFilename) {
    // 获取文件扩展名
    String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

    // 生成日期路径
    String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

    // 生成UUID
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");

    return String.format("user/%s/%s%s", datePath, uuid, extension);
  }
}
